Page({
  data: {
    cartList: [],
    totalPrice: 0,
    isLoggedIn: false
  },
  onShow() {
    this.checkLoginStatus();
    if (this.data.isLoggedIn) {
      this.getCartList();
    }
  },
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({
      isLoggedIn: !!userInfo
    });
  },
  getCartList() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) return;
    
    // 请求购物车数据
    wx.request({
      url: 'http://localhost:3000/api/cart',
      method: 'GET',
      data: { user_id: userInfo.id },
      success: (res) => {
        if (res.data && res.data.code === 0) {
          const cartList = res.data.data;
          // 计算总价
          let total = 0;
          cartList.forEach(item => {
            total += item.price * item.quantity;
          });
          this.setData({ cartList, totalPrice: total.toFixed(2) });
        }
      },
      fail() {
        wx.showToast({ title: '获取购物车失败', icon: 'none' });
      }
    });
  },
  removeCartItem(e) {
    const cartId = e.currentTarget.dataset.id;
    wx.request({
      url: 'http://localhost:3000/api/cart/' + cartId,
      method: 'DELETE',
      success: (res) => {
        if (res.data && res.data.code === 0) {
          wx.showToast({ title: '已删除', icon: 'success' });
          this.getCartList(); // 重新加载购物车
        } else {
          wx.showToast({ title: res.data.message || '删除失败', icon: 'none' });
        }
      },
      fail() {
        wx.showToast({ title: '删除失败', icon: 'none' });
      }
    });
  },
  checkout() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    
    wx.request({
      url: 'http://localhost:3000/api/order',
      method: 'POST',
      data: { user_id: userInfo.id },
      success: (res) => {
        if (res.data && res.data.code === 0) {
          wx.showToast({ title: '结算成功', icon: 'success' });
          this.getCartList(); // 结算后刷新购物车
        } else {
          wx.showToast({ title: res.data.message || '结算失败', icon: 'none' });
        }
      },
      fail() {
        wx.showToast({ title: '结算失败', icon: 'none' });
      }
    });
  },
  goToLogin() {
    wx.navigateTo({
      url: '/pages/user/login/index'
    });
  }
}); 